﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 简书 https://www.jianshu.com/p/36613a58ba33
/// 在拿到要显示的信息并在你的canvas内对要现实的信息处理完成之后 执行以下代码
/// 这里我是用背板image作为父物体，可以根据自己的实际需求修改
/// </summary>
public class CameraCapture : MonoBehaviour
{
    public GameObject captureCanvas;
    public Image imgBg;
    float m_multiplyNum = 1;

    void Awake()
    {
        float standardPhoneNum = 1080f / 1920f; //16:9 尺寸
        float phoneNum = (float)Screen.width / (float)Screen.height;

        CanvasScaler canvasScaler = captureCanvas.GetComponent<CanvasScaler>();
        canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand;
        //宽屏，pad等
        if (phoneNum > standardPhoneNum)
        {
            m_multiplyNum = m_camera.pixelHeight / 1920f;
        }
        else  //全面屏 mix p20 iphonex等
        {
            m_multiplyNum = m_camera.pixelWidth / 1080f;
        }
    }

    void Start()
    {
        Debug.Log("hankangwen");
        Debug.Log(StartRender(imgBg));
    }

    public Camera m_camera;
    private RenderTexture m_renderTexture;

    //ima为要分享的图片，分享时要保证此canvas下只打开要分享的相关物体
    private string StartRender(Image ima)
    {
        m_camera.enabled = true;
        //分局平台的不同设置分享图片显示的位置
        //pc或者iphone的起始点位于坐上
#if UNITY_EDITOR || UNITY_IPHONE
        ima.GetComponent<RectTransform>().SetPivot(PivotPresets.TopLeft);
        ima.GetComponent<RectTransform>().SetAnchor(AnchorPresets.TopLeft, 0, 0);
#elif UNITY_ANDROID   //安卓位于左下
        ima.GetComponent<RectTransform>().SetPivot(PivotPresets.BottomLeft);
        ima.GetComponent<RectTransform>().SetAnchor(AnchorPresets.BottomLeft, 0, 0);
#endif

        Rect rect = ima.GetComponent<RectTransform>().rect;
        rect.width = rect.width;
        rect.height = rect.height;
        //首次执行创建renderTexture,大小为相机渲染出的canvas的像素，并设置相机targetTexture
        if (m_renderTexture == null)
        {
            m_renderTexture = new RenderTexture(m_camera.pixelWidth, m_camera.pixelHeight, 24);
            m_renderTexture.Create();
            m_camera.targetTexture = m_renderTexture;
        }

        m_camera.Render();
        RenderTexture.active = m_renderTexture;
        //创建要分享出的texture2d 大小为ima的rect的宽、高乘之前计算的缩放比例
        Texture2D t = new Texture2D((int)(rect.width * m_multiplyNum), (int)(rect.height * m_multiplyNum), TextureFormat.ARGB32, true);
        //读取renderTexture内贴图大小的像素内保存在贴图内
        t.ReadPixels(new Rect(0, 0, t.width, t.height), 0, 0);
        //图片的名称，命名为分享的时间
        string name = System.DateTime.Now.ToString().Replace("/", "_");
        name = name.Replace(" ", "_");
        name = name.Replace(":", "_");
        //获取图片保存的路径
        string path = Application.persistentDataPath + "/sharePic/" + name + ".png";
        string directoryPath = Application.persistentDataPath + "/sharePic";
        //如果 com.xxx.xxx  下不存在 sharePic路径 创建该文件夹
        if (!Directory.Exists(directoryPath))
        {
            System.IO.Directory.CreateDirectory(directoryPath);
        }
        if (!File.Exists(path))
        {
            var bytes = t.EncodeToPNG();
            File.WriteAllBytes(path, bytes);
        }

#if !UNITY_EDITOR
        //防止全面屏手机穿透看到  如果不关闭会导致屏幕最下方出现此图片
        m_camera.enabled = false;
#endif
        //返回保存图片的路径
        return path;
    }

}
